from django.shortcuts import redirect
from django.urls import reverse
from django.utils.deprecation import MiddlewareMixin
from django.contrib import messages


class RbacAuthenticationMiddleware(MiddlewareMixin):
    def process_request(self, request):
        # 定义不需要登录即可访问的URL
        user_id = request.session.get('user_id')
        
        # 设置基础用户信息
        request.current_user = {
            'id': user_id,
            'username': request.session.get('username'),
            'email': request.session.get('email'),
            'first_name': request.session.get('first_name', ''),
            'last_name': request.session.get('last_name', ''),
            'role': request.session.get('role'),  # 保留兼容性
            'roles': request.session.get('roles', []),  # 新的角色列表
            'is_superuser': False  # 默认值
        }
        
        # 如果用户已登录，获取完整的用户信息
        if user_id:
            try:
                from rbac.models import RbacUser
                user = RbacUser.objects.get(id=user_id)
                request.current_user['is_superuser'] = user.is_superuser
            except:
                pass  # 如果查询失败，使用默认值
        
        # 直接放行登录和注册页面，不再执行后续检查
        public_paths = [
            '/rbac/login/', '/rbac/register/', '/rbac/logout/',
            '/admin/', '/login/', '/register/', '/logout/'
        ]
        if any(request.path_info.startswith(path) for path in public_paths):
            return None

        # 仅在需要登录的路径检查用户状态
        if not request.current_user['id']:
            return redirect('/rbac/login/')

        # 新的权限验证机制
        return self._check_permissions(request)
    
    def _check_permissions(self, request):
        """检查用户权限"""
        # 获取用户角色
        user_roles = request.current_user.get('roles', [])
        old_role = request.current_user.get('role', 'user')
        
        # 如果没有新角色，使用旧的角色系统逐渐迁移
        if not user_roles:
            return self._legacy_permission_check(request, old_role)
        
        # 新的权限检查逻辑
        return self._new_permission_check(request, user_roles)
    
    def _legacy_permission_check(self, request, role):
        """旧的权限检查机制（兼容性）"""
        # 原有的简单权限验证：普通用户无权访问用户管理和所有报告
        if role == 'user':
            restricted_paths = ['/user_management/', '/all_report_list/', '/rbac/user_management/', '/rbac/role_list/']
            if any(request.path_info.startswith(path) for path in restricted_paths):
                messages.error(request, '您没有权限访问此页面')
                return redirect('/rbac/')
        return None
    
    def _new_permission_check(self, request, user_roles):
        """新的基于角色权限的检查机制"""
        # 超级用户拥有所有权限
        if request.current_user.get('is_superuser', False):
            return None
            
        # 超级管理员角色有所有权限
        if 'super_admin' in user_roles:
            return None
        
        # 定义路径和所需权限的映射
        permission_map = {
            # 用户管理相关
            '/rbac/user_management/': 'user.list',
            
            # 角色管理相关
            '/rbac/role_list/': 'role.list',
            '/rbac/role_management/': 'role.list',
            '/rbac/role_add/': 'role.add',
            '/rbac/permission_list/': 'role.list',
            '/rbac/init_system_data/': 'role.manage_permissions',
            
            # 系统配置
            '/rbac/system/': 'system.config',
        }
        
        # 检查当前路径是否需要特定权限
        for path, required_permission in permission_map.items():
            if request.path_info.startswith(path):
                if not self._user_has_permission(request.current_user['id'], required_permission):
                    messages.error(request, '您没有权限访问此页面')
                    return redirect('/rbac/')
                break
        
        # 检查角色管理相关的POST请求
        if request.method == 'POST':
            if request.path_info.startswith('/rbac/role_edit/'):
                if not self._user_has_permission(request.current_user['id'], 'role.edit'):
                    messages.error(request, '您没有编辑角色的权限')
                    return redirect('/rbac/role_list/')
            elif request.path_info.startswith('/rbac/role_delete/'):
                if not self._user_has_permission(request.current_user['id'], 'role.delete'):
                    messages.error(request, '您没有删除角色的权限')
                    return redirect('/rbac/role_list/')
            elif request.path_info.startswith('/rbac/role_manage_permissions/'):
                if not self._user_has_permission(request.current_user['id'], 'role.manage_permissions'):
                    messages.error(request, '您没有管理权限的权限')
                    return redirect('/rbac/role_list/')
        
        return None
    
    def _user_has_permission(self, user_id, permission_code):
        """检查用户是否具有指定权限"""
        if not user_id:
            return False
        
        try:
            # 动态导入以避免循环导入
            from rbac.models import RbacUser
            user = RbacUser.objects.get(id=user_id)
            return user.has_permission(permission_code)
        except:
            return False